<template>
  <view class="page-cutImage">
	  <view class="cropper-buttons">
	    <view class="btn upload" @click="uploadTap">选择图片</view>
	    <view class="btn getCropperImage" @click="getCropperImage"> 确定 </view>
	  </view>
    <view class="cropper">
      <canvas
        v-if="_canvasId"
        :canvasId="_canvasId"
        @touchstart="touchstart"
        @touchmove="touchmove"
        @touchend="touchend"
        disable-scroll
        :style="{
          width: _width + 'px',
          height: _height + 'px',
          background: 'rgba(0, 0, 0, .1)',
        }"
      >
      </canvas>
      <canvas
        v-if="_targetId"
        :canvas-id="_targetId"
        disable-scroll
        :style="{
          position: 'absolute',
          top: -_width * _pixelRatio + 'px',
          left: -_height * _pixelRatio + 'px',
          width: _width * _pixelRatio + 'px',
          height: _height * _pixelRatio + 'px',
        }"
      >
      </canvas>
    </view>
    
  </view>
</template>

<script>
import WeCropper from "../../utils/we-cropper.js";
import allapi from "../../api/index.js";
const device = wx.getSystemInfoSync();
const width = device.windowWidth;
const height = device.windowHeight - 85;
export default {
  components: {},
  data() {
    return {
      cropperOpt: {
        id: "cropper",
        targetId: "targetCropper",
        pixelRatio: device.pixelRatio,
        width,
        height,
        scale: 2.5,
        zoom: 8,
        cut: {
          x: (width - 375) / 2,
          y: (height - 375) / 2 - 60,
          width: 375,
          height: 375,
        },
        boundStyle: {
          color: "#ccc",
          mask: "rgba(0,0,0,0.8)",
          lineWidth: 1,
        },
      },
      //   cropper: "",
      _wecropper: null,
      imgUrl: "", // 上传图片的临时地址
    };
  },
  computed: {
    _canvasId() {
      return this.cropperOpt.id;
    },
    _targetId() {
      return this.cropperOpt.targetId;
    },
    _width() {
      return this.cropperOpt.width;
    },
    _height() {
      return this.cropperOpt.height;
    },
    _pixelRatio() {
      return this.cropperOpt.pixelRatio;
    },
  },
  methods: {
    touchstart($event) {
      console.log("touchstart---", $event);
      this._wecropper.touchStart($event.mp);
    },
    touchmove($event) {
      this._wecropper.touchMove($event.mp);
    },
    touchend($event) {
      this._wecropper.touchEnd($event.mp);
    },
    pushOrigin(src) {
      this._wecropper.pushOrign(src);
    },
    updateCanvas() {
      this._wecropper.updateCanvas();
    },
    getCropperBase64(fn) {
      return this._wecropper.getCropperBase64(fn);
    },
    init() {
      return new Promise((resolve,reject)=>{
          this._wecropper = new WeCropper(
            Object.assign(this.cropperOpt, {
              id: this._canvasId,
              targetId: this._targetId,
              pixelRatio: this._pixelRatio,
              vueThis: this,
            })
          )
            .on("ready", (...args) => {
              this.$emit("ready", ...args);
              resolve()
            })
            .on("beforeImageLoad", (...args) => {
              this.$emit("beforeImageLoad", ...args);
            })
            .on("imageLoad", (...args) => {
              this.$emit("imageLoad", ...args);
            })
            .on("beforeDraw", (...args) => {
              this.$emit("beforeDraw", ...args);
              
            });
          })

    },
    getCropperImage() {
      if (!this.imgUrl) {
        uni.showToast({
          title: "请先选择图片",
          icon: "none",
          duration: 1500,
        });
        return;
      }
      this._wecropper.getCropperImage((path, err) => {
        if (err) {
          uni.showModal({
            title: "温馨提示",
            content: err.message,
          });
        } else {
          console.log('path',path)
          uni.showLoading({
            title: "上传中……",
          });
          uni.uploadFile({
            url: allapi.upload,
            filePath: path,
            name: "file",
            success: (uploadFileRes) => {
              wx.hideLoading();
              let dat = uploadFileRes.data;
              let msg = JSON.parse(dat);
              let imgurl = msg.url;
              this.$store.commit("image/src/UPDATE", imgurl);
              uni.navigateBack();
            },
            fail: () => {
              wx.hideLoading();
            },
          });
        }
      });
    },
    uploadTap() {
      uni.chooseImage({
        count: 1, // 默认9
        sizeType: ["compressed"],
        sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
        success: (res) => {
          const src = res.tempFilePaths[0];
          //  获取裁剪图片资源后，给data添加src属性及其值
          this.imgUrl = src;
          this._wecropper.pushOrign(src);
        },
        fail() {
          console.log("上传失败");
        },
      });
    },
  },
  onLoad(option) {
    this.imgUrl=option.src
    this.$store.commit("image/src/UPDATE", '');
  },
  mounted() {
    this.init().then(()=>{
      this._wecropper.pushOrign(this.imgUrl);
    })
    // this._wecropper.pushOrigin(
    //   "http://tmp/RPendCGS2Lcf30a6202c89fb07177da3f77e70cc14ff.jpg"
    // );
    // this.cropperOpt.src = 'http://tmp/RPendCGS2Lcf30a6202c89fb07177da3f77e70cc14ff.jpg'
  },
};
</script>

<style lang="less">
/* @import "../../style/common.wxss"; */
page {
  height: 100%;
}
.page-cutImage {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #e5e5e5;
  overflow: hidden;
}

.cropper-buttons {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  // position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  //   min-height: 100rpx;
  height: 85px;
  padding: 24rpx 40rpx;
  // padding-bottom: calc(env(safe-area-inset-bottom) + 24rpx);
  box-sizing: border-box;
  background-color: rgba(0, 0, 0, 1);
  z-index: 999;
  border-bottom: 1rpx solid #ccc;
  .btn {
    height: 60rpx;
    line-height: 60rpx;
    padding: 0 24rpx;
    border-radius: 4rpx;
    color: #ffffff;
    text-align: center;
    &.upload {
    }
    &.getCropperImage {
      background: #28cd50;
    }
  }
}

.cropper {
  // position: absolute;
  top: 0;
  left: 0;
  flex: 1;
  overflow: hidden;
}
</style>